package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.entity.Admin;
import com.atguigu.entity.Permission;
import com.atguigu.service.AdminService;
import com.atguigu.service.PermissionService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping
public class IndexController {
    @Reference
    private AdminService adminService;
    @Reference
    private PermissionService permissionService;
    // 首页：默认欢迎页
    @GetMapping("/")
    public String index(Model model) {
        // 暂时用默认ID为管理员
//        Long adminId = 1L;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user = (User)authentication.getPrincipal();
        // 调用adminService中查询方法
//        Admin admin = adminService.getById(adminId);
        Admin admin = adminService.getByUsername(user.getUsername());
        // 由用户id调用permissionService中获取用户权限的方法
        List<Permission> permissionList = permissionService.findMenuPermissionByAdminId(admin.getId());
        model.addAttribute("admin", admin);
        model.addAttribute("permissionList",permissionList);
        return "frame/index";
    }

    // 框架主页：访问首页（frame/index）时，浏览器发起/main请求
    @GetMapping("/main")
    public String main() {
        return "frame/main";
    }

    @GetMapping("/login")
    public String toLogin(){
        return "frame/login";
    }

    // 登录成功后获取用户信息
    /*
     登录成功后访问：http://localhost:5008/getInfo
        {
            "accountNonExpired": true,
            "accountNonLocked": true,
            "authorities": [],
            "credentialsNonExpired": true,
            "enabled": true,
            "username": "admin"
        }
     */
    @GetMapping("/getInfo")
    @ResponseBody
    public Object getInfo(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication.getPrincipal();
    }
    // auth
    @GetMapping("/auth")
    public String auth() {
        // 转跳
        return "frame/auth";
    }

}
